package com.ys.peony.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.yklab.library.refreshlayout.adapters.NewCommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;
import com.yklab.library.ui.adapter.LoadMoreWrapper;
import com.yklab.library.util.StringUtils;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.DaimianshenModel;
import com.ys.peony.model.DaimianshenResp;
import com.ys.peony.model.UserModel;
import com.ys.peony.model.domain.ContractSortModel;
import com.ys.peony.ui.view.DialogContract;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContractListActivity extends ListActivity<DaimianshenModel> implements OnClickCommonListener {

    @Override
    protected int getContentResId() {
        return super.getContentResId();
    }

    @Override
    protected void initView() {
        setShowToolbar(true);
        super.initView();
        toolbar.setTitle("客户签约列表");
        initAdapter();
        //数据请求
        refreshlayout.beginRefreshing();
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mAdapter = new NewCommonRecyclerViewAdapter<DaimianshenModel>(this, mList, R.layout.daimianshen_view_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                DaimianshenModel model = mList.get(position);
                ((CommonRecyclerViewHolder) holder).setText(R.id.tv_business_num, StringUtils.isEmpty(model.getSerial_number()) ? "" : model.getSerial_number())
                        .setText(R.id.tv_business_state, StringUtils.isEmpty(model.getTask_name()) ? BusinessDetailStatus.getStatus(model.getLoan_status()) : model.getTask_name())
                        .setText(R.id.tv_shopname, StringUtils.isEmpty(model.getShop_org_name()) ? "" : model.getShop_org_name())
                        .setText(R.id.tv_customerType, StringUtils.isEmpty(model.getClient_clas_name()) ? "" : model.getClient_clas_name())
                        .setText(R.id.tv_name, StringUtils.isEmpty(model.getClient_name()) ? "" : model.getClient_name())
                        .setImgResource(R.id.jiekuan_icon, R.mipmap.dianqianitem);
                //业务归属
                String name = TextUtils.isEmpty(model.getClient_res_str()) ? "" : model.getClient_res_str();
                String[] temp = name.split("：");
                if (temp.length >= 2) {
                    ((CommonRecyclerViewHolder) holder).setText(R.id.tv_ownership, TextUtils.isEmpty(temp[1]) ? "" : temp[1]);
                }
            }
        };
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter.setOnClickListener(this);
        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        recyclerview.setHasFixedSize(true);
        recyclerview.addItemDecoration(new Divider(this));
        recyclerview.setLayoutManager(mLayoutManager);
        recyclerview.setAdapter(mLoadMoreWrapper);
    }

    @Override
    protected void getData() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return;
        }
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", Long.parseLong(userModel.getId()));
        params.put("currentPage", curPageNum);
        params.put("pageNum", pageNum);
        httpManagerUtils.get(getUrl(), params, new BaseRespCallBack(this) {
            @Override
            public void onRespSuccess(String respStr) {
                refreshlayout.endRefreshing();
                setData(respStr);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                refreshlayout.endRefreshing();
                showBlankView();
            }
        });
    }

    @Override
    protected String getUrl() {
        return HttpURL.clientContractList;
    }

    private void setData(final String data) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                DaimianshenResp resp = JSONUtil.parseObject(data, DaimianshenResp.class);
                if (actionType == YSConstant.ACTION_TYPE_DOWN && (resp == null || resp.getDataList() == null || resp.getDataList().size() < 1)) {
                    showBlankView();
                    return;
                }
                List<DaimianshenModel> list = resp.getDataList();
                if ((list == null || list.size() < 1) && actionType == YSConstant.ACTION_TYPE_UP) {
                    mLoadMoreWrapper.setLoadState(LoadMoreWrapper.LOADING_END);
                    return;
                }
                if (actionType == YSConstant.ACTION_TYPE_DOWN) {
                    hideBlankView();
                    mList.clear();
                    mRequestList.clear();
                    mList.addAll(list);
                    mRequestList.addAll(list);
                    mLoadMoreWrapper.notifyDataSetChanged();
                } else if (actionType == YSConstant.ACTION_TYPE_UP) {
                    mList.addAll(list);
                    mRequestList.addAll(list);
                    mLoadMoreWrapper.notifyItemRangeInserted(mList.size() - list.size() + 1, list.size());
                }
            }
        });
    }

    @Override
    public void onClickListener(View view, int position) {
        doRequestContract(mList.get(position));
    }

    private void doRequestContract(final DaimianshenModel daimianshenModel) {
        LoadingProgressUtils.showProgressDialog(this);
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loan_id", daimianshenModel.getId());
        httpManagerUtils.get(HttpURL.contractList, params, new BaseRespCallBack(this) {
            @Override
            public void onRespSuccess(String respStr) {
                ContractSortModel contractSortModel = JSONUtil.parseObject(respStr, ContractSortModel.class);
                if (contractSortModel != null && contractSortModel.getFileTemplate() != null) {
                    if ("1".equals(contractSortModel.getFlag_sign())) {
                        showDialog(respStr, daimianshenModel, contractSortModel.getBusiClient().getMobile());
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString(YSConstant.PARAM, daimianshenModel.getId());
                        bundle.putString("data", respStr);
                        bundle.putString("name", daimianshenModel.getClient_name());
                        skipToTargetPage(ContractSortListActivity.class, bundle);
                    }
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                //showBlankView();
            }
        });
    }

    private void showDialog(final String data, final DaimianshenModel daimianshenModel, final String phone) {
        DialogContract dialog = new DialogContract(this);
        dialog.setData(data, daimianshenModel, phone);
    }

    @Override
    public void observerSearchText(List list, String text) {
        mList.clear();
        for (int i = 0; i < list.size(); i++) {
            DaimianshenModel daimianshenModel = (DaimianshenModel) list.get(i);
            if (!"".equals(text) && (daimianshenModel.getSerial_number().contains(text) || daimianshenModel.getClient_name().contains(text))) {
                mList.add(daimianshenModel);
            }
        }
        mLoadMoreWrapper.notifyDataSetChanged();
    }

    @Override
    protected void searchData(String respStr) {
        final DaimianshenResp resp = JSONUtil.parseObject(respStr, DaimianshenResp.class);
        if (resp != null && resp.getDataList() != null) {
            mList.clear();
            mList.addAll(resp.getDataList());
            mLoadMoreWrapper.notifyDataSetChanged();
        }
    }

}
